package com.service.thirddatacenter.framework.exception;

import com.service.core.constant.BusinessStatus;
import com.service.core.exception.CommonException;
import com.service.core.rest.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Description: CommonExceptionHandler
 */
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * 自定义异常
     */
    @ExceptionHandler(CommonException.class)
    public BaseResponse handleRRException(CommonException e) {
        return new BaseResponse(e.getCode(),  e.getMsg());
    }

    /**
     * 处理必要参数未传递的handler
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("必要参数未传递", e);
        return new BaseResponse(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    /**
     * 处理参数校验失败的异常handler
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        final BindingResult bindingResult = e.getBindingResult();
        final FieldError errors = bindingResult.getFieldErrors().get(0);
        log.error("参数校验未通过: {},异常原因:{}", errors.getField(), errors.getDefaultMessage(), e);
        return new BaseResponse(BusinessStatus.ARGS_ERROR.value(), e.getMessage());
    }

    /**
     * 请求内容解析错误的handler
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数错误:{}", e.getMessage());
        return new BaseResponse(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    /**
     * 处理其他异常handler
     */
    @ExceptionHandler(Exception.class)
    public BaseResponse handleException(Exception e) {
        e.printStackTrace();
        log.error("异常原因:{}", e.getLocalizedMessage());
        return new BaseResponse(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase());
    }
}
